package com.yss.netty.util;

import com.yss.exception.RouterParallelException;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.net.InetSocketAddress;

@Data
@EqualsAndHashCode(of = {"address"})
public class Host {

    private String ip;

    private int port;

    private String address;

    private String resourceUrl;

    public Host(String resourceUrl) {
        this.resourceUrl = resourceUrl;
    }

    public Host(String ip, int port) {
        this.ip = ip;
        this.port = port;
        this.address = ip + Constants.COLON + port;
    }

    public static Host of(String ip, int port) {
        return new Host(ip, port);
    }

    public static Host of(InetSocketAddress inetSocketAddress) {
        return new Host(
                inetSocketAddress.getHostString(),
                inetSocketAddress.getPort()
        );
    }

    public static Host ofResourceUrl(String resourceUrl) {
        return new Host(resourceUrl);
    }

    /**
     * @param ipColonPort Like this: 127.0.0.1:8888
     * @return
     */
    public static Host of(String ipColonPort) {
        if (!ipColonPort.contains(Constants.COLON)) {
            throw new RouterParallelException(String.format("Server IpPort configuration error %s", ipColonPort));
        }
        try {
            String[] ipPort = ipColonPort.split(Constants.COLON);
            return new Host(ipPort[0], Integer.valueOf(ipPort[1]));
        } catch (Exception e) {
            throw new RouterParallelException(String.format("Server IpPort configuration error %s", ipColonPort));
        }
    }

}
